package com.sunyard.manage.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sunyard.constant.manage.RoleConst;
import com.sunyard.dal.bo.bulletin.BulletinAddBO;
import com.sunyard.dal.bo.bulletin.BulletinDeleteBO;
import com.sunyard.dal.bo.bulletin.BulletinDetailBO;
import com.sunyard.dal.bo.bulletin.BulletinQueryBo;
import com.sunyard.dal.bo.bulletin.BulletinUpdateBO;
import com.sunyard.dal.bo.PaginationBO;
import com.sunyard.dal.dto.BulletinDTO;
import com.sunyard.dal.entity.Bulletin;
import com.sunyard.dal.entity.BulletinRel;
import com.sunyard.dal.entity.Operator;
import com.sunyard.dal.entity.Organization;
import com.sunyard.dal.mapper.BulletinMapper;
import com.sunyard.dal.mapper.BulletinRelMapper;
import com.sunyard.dal.mapper.OperatorMapper;
import com.sunyard.dal.mapper.OrganizationMapper;
import com.sunyard.manage.service.BulletinService;
import com.sunyard.manage.service.OperatorLogService;
import com.sunyard.utils.DtoUtils;
import com.sunyard.utils.PrimaryKeyUtil;
import com.sunyard.utils.Response.BaseResult;
import com.sunyard.utils.Response.GetResult;
import com.sunyard.utils.TokenUtil;
import com.sunyard.utils.manage.DataGrid;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class BulletinServiceImpl implements BulletinService {

    @Autowired
    BulletinMapper bulletinMapper;
    @Autowired
    OrganizationMapper organizationMapper;
    @Autowired
    BulletinRelMapper bulletinRelMapper;
    @Autowired
    OperatorMapper operatorMapper;
    @Autowired
    private OperatorLogService operatorLogService;


    @Override
    public BaseResult<DataGrid<BulletinDTO>> getBulletinList(HttpServletRequest request,
                                                             PaginationBO<BulletinQueryBo> bulletinQueryBoPaginationBO) {
        String opId = TokenUtil.getOpId(request.getHeader("token"));

        BulletinQueryBo bulletinQueryBo = bulletinQueryBoPaginationBO.getParams();
        //当前系统登陆人id
        bulletinQueryBo.setLoginOpId(opId);
        if (StringUtils.isNotBlank(bulletinQueryBo.getStartDateTime())){
            bulletinQueryBo.setStartDateTime(bulletinQueryBo.getStartDateTime() + " 00:00:00");
        }
        if (StringUtils.isNotBlank(bulletinQueryBo.getEndDateTime())){
            bulletinQueryBo.setEndDateTime(bulletinQueryBo.getEndDateTime() + " 23:59:59");
        }

        //设置分页信息
        PageHelper.startPage(bulletinQueryBoPaginationBO.getPageNo(), bulletinQueryBoPaginationBO.getPageSize());
        List<BulletinDTO> bulletinDTOList = bulletinMapper.getBulletinList(bulletinQueryBo);
        //取分页信息
        PageInfo<BulletinDTO> pageInfo = new PageInfo<>(bulletinDTOList);
        //设置返回结果
        DataGrid<BulletinDTO> dataGrid = new DataGrid<>();
        long total = pageInfo.getTotal();
        dataGrid.setTotal((int) total);
        dataGrid.setRows(bulletinDTOList);
        return GetResult.getResult(dataGrid);
    }

    @Override
    public BaseResult<DataGrid<String>> getOrgByBulletinId(HttpServletRequest request, BulletinQueryBo bulletinQueryBo) {
        List<String> orgIds = bulletinMapper.getOrgByBulletinId(bulletinQueryBo.getBulletinId());
        //设置返回结果
        DataGrid<String> dataGrid = new DataGrid<>();
        dataGrid.setRows(orgIds);
        return GetResult.getResult(dataGrid);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public BaseResult addBulletin(HttpServletRequest request, BulletinAddBO bulletinAddBO) throws Exception {
        String opId = TokenUtil.getOpId(request.getHeader("token"));
        String opName = TokenUtil.getOpName(request.getHeader("token"));
        String orgId = TokenUtil.getOrgId(request.getHeader("token"));
        //定义日志信息
        String logName = "添加公告";
        String operationDesc = "用户" + opName + "添加公告，标题为：" + bulletinAddBO.getTitleName();
        Organization organization = organizationMapper.getOrganizationByOrgId(orgId);
        Bulletin bulletin = new Bulletin();
        bulletin.setBulletinId(PrimaryKeyUtil.getPrimaryKey(RoleConst.BULLETIN_ID));
        bulletin.setOpId(opId);
        bulletin.setOpName(opName);
        bulletin.setOrgId(orgId);
        bulletin.setOrgName(organization.getOrgName());
        bulletin.setRevocation("0");
        DtoUtils.cloneBeanToBean(bulletin, bulletinAddBO);
        //获取公告接收机构下所有的人员id
        List<Operator> operatorList = operatorMapper.getOperatorByOrgIds(bulletinAddBO.getNewBulletinOrgIdList());
        //添加公告信息表
        int result = bulletinMapper.insert(bulletin);
        //组装公告人员关联信息 插入关联表
        BulletinRel bulletinRel = new BulletinRel();
        bulletinRel.setHasRead("0");
        bulletinRel.setIsDelete("0");
        bulletinRel.setBulletinId(bulletin.getBulletinId());
        for (Operator operator : operatorList) {
            bulletinRel.setOpId(operator.getOpId());
            bulletinRel.setOrgId(operator.getOrgId());
            bulletinRelMapper.insert(bulletinRel);
        }
        /*if (true){
            throw new RuntimeException();
        }*/
        if (result > 0) {
            operatorLogService.insert(operationDesc, logName, "1", opId, opName, orgId);
            return GetResult.getResultSuccess("发布成功！");
        }
        return GetResult.getResultErr("发布失败！");
    }

    /**
     * 批量删除公告，删除后所有人都无法查看该公告
     *
     * @param request
     * @param bulletinDeleteBO [request, bulletinDeleteBO]
     * @return BaseResult
     * @author: guangw.dang
     * @Date: 2022/8/24 16:46
     **/
    @Override
    @Transactional(rollbackFor = Exception.class)
    public BaseResult delBulletin(HttpServletRequest request, BulletinDeleteBO bulletinDeleteBO) {
        String opId = TokenUtil.getOpId(request.getHeader("token"));
        String opName = TokenUtil.getOpName(request.getHeader("token"));
        String orgId = TokenUtil.getOrgId(request.getHeader("token"));
        //定义日志信息
        String logName = "删除公告";
        String operationDesc = "用户" + opName + "删除公告，编号为：" + bulletinDeleteBO.getBulletinIds();
        Map<String, Object> updateMap = new HashMap<>();
        updateMap.put("bulletinIds", bulletinDeleteBO.getBulletinIds());
        //逻辑删除
        int result = bulletinRelMapper.updateRelBybulletinIds(updateMap);
        bulletinMapper.delete(bulletinDeleteBO);
        if (result > 0) {
            operatorLogService.insert(operationDesc, logName, "1", opId, opName, orgId);
            /*if (true){
                throw new RuntimeException();
            }*/
            return GetResult.getResultSuccess("删除成功！");
        }
        return GetResult.getResultErr("删除失败！");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public BaseResult edit(HttpServletRequest request, BulletinUpdateBO bulletinUpdateBO) {
        String opId = TokenUtil.getOpId(request.getHeader("token"));
        String opName = TokenUtil.getOpName(request.getHeader("token"));
        String orgId = TokenUtil.getOrgId(request.getHeader("token"));
        //定义日志信息
        String logName = "公告修改";
        String operationDesc = "用户" + opName + "修改公告，标题为：" + bulletinUpdateBO.getTitleName();
        //第一次查询当前公告通知的机构ID 对比出需要删除的机构ID
        List<String> oldBulletinOrgIdList = bulletinRelMapper.getOrgIdList(bulletinUpdateBO);
        //需要删除的机构id
        oldBulletinOrgIdList.removeAll(bulletinUpdateBO.getNewBulletinOrgIdList());
        List<String> delBulletinOrgIdList = new ArrayList<>(oldBulletinOrgIdList);
        if (!delBulletinOrgIdList.isEmpty()) {
            //逻辑删除掉不需要接收公告的机构下的用户
            bulletinRelMapper.updateRelByOrgId(delBulletinOrgIdList);
        }

        //第二次查询当前公告通知的机构id 对比出需要新增的机构ID
        List<String> oldBulletinOrgIdList2 = bulletinRelMapper.getOrgIdList2(bulletinUpdateBO);
        //新增需要发布的机构ID
        bulletinUpdateBO.getNewBulletinOrgIdList().removeAll(oldBulletinOrgIdList2);
        List<String> addBulletinOrgIdList = new ArrayList<>(bulletinUpdateBO.getNewBulletinOrgIdList());
        if (addBulletinOrgIdList.isEmpty()) {
            //修改发布公告信息 以及 发布公告接收的机构
            int updResult = bulletinMapper.update(bulletinUpdateBO);
            if (updResult > 0) {
                return GetResult.getResultSuccess("修改成功！");
            }
            return GetResult.getResultErr("修改失败！");
        }
        //修改发布公告信息 以及 发布公告接收的机构
        int updResult = bulletinMapper.update(bulletinUpdateBO);
        //获取公告接收机构下所有的人员id
        List<Operator> operatorList = operatorMapper.getOperatorByOrgIds(addBulletinOrgIdList);
        BulletinRel bulletinRel = new BulletinRel();
        bulletinRel.setHasRead("0");
        bulletinRel.setIsDelete("0");
        bulletinRel.setBulletinId(bulletinUpdateBO.getBulletinId());
        for (Operator operator : operatorList) {
            bulletinRel.setOpId(operator.getOpId());
            bulletinRel.setOrgId(operator.getOrgId());
            bulletinRelMapper.insert(bulletinRel);
        }
        if (updResult > 0) {
            operatorLogService.insert(operationDesc, logName, "1", opId, opName, orgId);
            return GetResult.getResultSuccess("修改成功！");
        }
        return GetResult.getResultErr("修改失败！");
    }

    @Override
    public BaseResult<Bulletin> detail(HttpServletRequest request, BulletinDetailBO bulletinDetailBO) {
        String opId = TokenUtil.getOpId(request.getHeader("token"));
        String orgId = TokenUtil.getOrgId(request.getHeader("token"));
        String opName = TokenUtil.getOpName(request.getHeader("token"));
        operatorLogService.insert("用户"+ opName + "查看公告详情，id为" + bulletinDetailBO.getBulletinId(),  "查看公告详情", "1", opId, opName, orgId);
        Bulletin bulletin = bulletinMapper.getDetailByBulletinId(bulletinDetailBO.getBulletinId());
        //用户查询了公告详情后 状态变为已读
        bulletinMapper.updateRelByOpId(opId);
        return GetResult.getResult(bulletin);
    }

    @Override
    public List<BulletinDTO> getListBulletinExport(HttpServletRequest request, BulletinQueryBo bulletinQueryBo) {
        return bulletinMapper.getBulletinList(bulletinQueryBo);
    }
}
